package com.example.planegame;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.view.KeyEvent;
import android.view.View;

public class PlaneView extends View {

    final private int speed = 10;
    private Bitmap bmPlane;
    private int bmWidth;
    private int bmHeight;
    private int screenWidth;
    private int screenHeight;
    private int currentX;
    private int currentY;

    public PlaneView(Context context) {
        super(context);
        currentX = currentY = 0;
        bmPlane = BitmapFactory.decodeResource(getResources(), R.drawable.plane);
        bmWidth = bmPlane.getWidth();
        bmHeight = bmPlane.getHeight();
        setBackgroundResource(R.drawable.back);
        setFocusable(true);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        Paint p = new Paint();
        screenWidth = getWidth();
        screenHeight = getHeight();
        currentX = currentX < 0 ? 0 : currentX;
        currentY = currentY < 0 ? 0 : currentY;
        currentX = currentX > screenWidth - bmWidth ? screenWidth - bmWidth
                : currentX;
        currentY = currentY > screenHeight - bmHeight ? screenHeight - bmHeight
                : currentY;
        canvas.drawBitmap(bmPlane, currentX, currentY, p);
    }

    public void offX(int dx) {
        currentX += dx;
        invalidate();
    }

    public void offY(int dy) {
        currentY += dy;
        invalidate();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_DPAD_DOWN:
                offY(speed);
                break;
            case KeyEvent.KEYCODE_DPAD_UP:
                offY(-speed);
                break;
            case KeyEvent.KEYCODE_DPAD_LEFT:
                offX(-speed);
                break;
            case KeyEvent.KEYCODE_DPAD_RIGHT:
                offX(speed);
                break;
        }
        return super.onKeyDown(keyCode, event);
    }
}